package com.jiezhuo.controller.jss;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiezhuo.entity.LoginUser;
import com.jiezhuo.entity.cmeduSchool.TJzg;
import com.jiezhuo.entity.cmeduSchool.XxdwUserlist;
import com.jiezhuo.entity.cmeduSchool.XxdwXq;
import com.jiezhuo.entity.jssgl.JssStuYd;
import com.jiezhuo.entity.jssgl.JssXtUserlist;
import com.jiezhuo.entity.jzg.JzgUserlist;
import com.jiezhuo.entity.jzg.TJzgUser;
import com.jiezhuo.service.cmeduSchool.XxdwService;
import com.jiezhuo.service.cmeduSchool.XxdwXqService;
import com.jiezhuo.service.jss.JssXtUserlistService;
import com.jiezhuo.service.jzg.TJzgService;
import com.jiezhuo.service.jzg.TJzgUserService;
import com.jiezhuo.utils.ListUtils;
import com.jiezhuo.utils.R;
import com.jiezhuo.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务控制器
 *
 * @author kancy
 * @description 由 Mybatisplus Code Generator 创建
 * @since 2024-06-13 08:48:15
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@Api(tags = "寄宿生管理--用户管理")
@RequestMapping("/jssXtUserlist")
@Transactional
public class JssXtUserlistController {
    private final JssXtUserlistService jssXtUserlistService;

    @Autowired
    private final TJzgService tJzgService;


    private final TJzgUserService tJzgUserService;

    // 字典读取
    private final XxdwService xxdwService;


    @Autowired
    XxdwXqService xxdwXqService;

    @ApiOperation("获取当前登录的用户信息")
    @GetMapping("getCurrentUserInfo")
    public R getCurrentUserInfo() {
        JssXtUserlist adminUserOne = jssXtUserlistService.getAdminUserOne();
        return R.ok().data("data", adminUserOne);
    }


    @ApiOperation("增加操作 加载老师loadDataFilter")
    @GetMapping("getTeacherLoadData")
    public R getTeacherLoadData(@RequestParam("xqdm") String xqdm) {
        QueryWrapper<TJzg> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("TeacherId", "XM");
        queryWrapper.eq("ReMoved", "0");
        queryWrapper.eq("GZ_XQDM", xqdm);
        queryWrapper.orderByAsc("XM");
        List<TJzg> list = tJzgService.list(queryWrapper);
        return R.ok().data("data", list);
    }


    @ApiOperation("增加操作 加载学校loadDataFilter")
    @GetMapping("getLoadDataFilter")
    public R getLoadDataFilter() {
//        string s = @"SELECT [XQJC],[NEW_XQDM] FROM [JCXX]..[T_XXDW_XQ] where DQZT='1' " + sqlt + " order by XQJC";
        QueryWrapper<XxdwXq> xxdwXqQueryWrapper = new QueryWrapper<>();
        xxdwXqQueryWrapper.select("XQJC", "NEW_XQDM");
        xxdwXqQueryWrapper.eq("DQZT", "1");
        if (jssXtUserlistService.isRoleXiao()) {
            xxdwXqQueryWrapper.eq("NEW_XQDM", jssXtUserlistService.getAdminUserOne().getJzg().getGzXqdm());
        }
        xxdwXqQueryWrapper.orderByAsc("XQJC");
        List<XxdwXq> xxdwXqList = xxdwXqService.list(xxdwXqQueryWrapper);
        return R.ok().data("data", xxdwXqList);
    }

    @ApiOperation("加载用户岗位状态")
    @GetMapping("getGwztStart")
    public R getGwztStart(String teacherId) {
        List<Map<String, Object>> maps = tJzgService.jssUserSaveLoad(teacherId);
        return R.ok().data("data", maps);
    }

    @ApiOperation("获取系统管理用户")
    @GetMapping("getUserList")
    public R getUserList(JssXtUserlist jssXtUserlist) {
        if (jssXtUserlistService.isRoleXiao()) {
            jssXtUserlist.setGz_xqdm(jssXtUserlistService.getAdminUserOne().getJzg().getGzXqdm());
        }

        // 获取字典 DM_SYZT
        List<Map<String, Object>> dm_syzt = xxdwService.getDistList("dm_syzt");

        //获取字典 DM_JZG_GWZT
        List<Map<String, Object>> dm_jzg_gwzt = xxdwService.getDistList("dm_jzg_gwzt");

//        if (StringUtils.isStringExist(jssStu.getYxqdm())) {
//            jssStuYdQueryWrapper.eq("YXQDM", jssStu.getYxqdm());
//        }
        // 所有的用户id
        Set<String> allUserId = null;

        //  获取 人员的用户标识
//        QueryWrapper<JssXtUserlist> queryWrapper = new QueryWrapper<>();
//        Page<JssXtUserlist> page = new Page<>();
//        page.setCurrent(jssXtUserlist.getCurrent()).setSize(jssXtUserlist.getSize());
        List<JssXtUserlist> records = jssXtUserlistService.list();

        allUserId = records.stream().map(JssXtUserlist::getUserid).collect(Collectors.toSet());

        // 获取教职工人员 信息
        QueryWrapper<TJzg> tJzglistQueryWrapper = new QueryWrapper<>();
        tJzglistQueryWrapper.in("TeacherId", allUserId);
        List<TJzg> tJzgList = tJzgService.list(tJzglistQueryWrapper);

        for (TJzg tJzg : tJzgList) {
            JssXtUserlist record = records.stream().filter(x -> x.getUserid().equalsIgnoreCase(tJzg.getTeacherid())).findFirst().get();

            List<Map<String, Object>> dm = dm_jzg_gwzt.stream().filter(x -> x.get("DM").toString().equalsIgnoreCase(tJzg.getGwzt())).collect(Collectors.toList());
            if (dm.size() != 0) {
                record.setGwzt(dm.get(0).get("MC").toString());
            }
        }

        //设置学校简称
        List<XxdwXq> xxdwXqList = xxdwXqService.list();
        Map<String, String> xxdmxqMap = new HashMap<>();
        for (XxdwXq xxdwXq : xxdwXqList) {
            xxdmxqMap.put(xxdwXq.getNewXqdm(), xxdwXq.getXqjc());
        }

        // 设置校区代码
        for (JssXtUserlist record : records) {
            TJzg jzg = tJzgList.stream().filter(x -> x.getTeacherid().equals(record.getUserid())).findFirst().get();
            record.setGz_xqdm(jzg.getGzXqdm());
            record.setGz_xqdmMc(xxdmxqMap.get(jzg.getGzXqdm()));
            record.setXm(jzg.getXm());
            record.setTeacherId(jzg.getTeacherid());
        }

        //  获取登录的用户
        QueryWrapper<TJzgUser> tJzgUserQueryWrapper = new QueryWrapper<>();
        tJzgUserQueryWrapper.in("TeacherId", allUserId);
        List<TJzgUser> tJzgUsers = tJzgUserService.list(tJzgUserQueryWrapper);


        for (JssXtUserlist record : records) {
            // 设置Login_ID
            TJzgUser tJzgUser = tJzgUsers.stream().filter(x -> x.getTeacherid().equals(record.getUserid())).findFirst().get();
            record.setLogin_id(tJzgUser.getLoginId());

            // 设置当前系统状态
            Map<String, Object> map = dm_syzt.stream().filter(x -> x.get("DM").toString().equalsIgnoreCase(tJzgUser.getSyzt())).findFirst().get();
            record.setSyzt(map.get("MC").toString());
        }
        Map<String, Object> hashMap = new HashMap<String, Object>();


        if (jssXtUserlist.getGz_xqdm() != null && !"".equals(jssXtUserlist.getGz_xqdm())) {
            records = records.stream().filter(x -> x.getGz_xqdm().equals(jssXtUserlist.getGz_xqdm())).collect(Collectors.toList());
        }

        if (jssXtUserlist.getXm() != null && !"".equals(jssXtUserlist.getXm())) {
            records = records.stream().filter(x -> x.getXm().contains(jssXtUserlist.getXm())).collect(Collectors.toList());
        }

        hashMap.put("count", records.size());
        if (records.size() != 0) {
            records = (List<JssXtUserlist>) ListUtils.subList(records, jssXtUserlist.getSize(), jssXtUserlist.getCurrent());
        }
        hashMap.put("data", records);
        return R.ok().data("data", hashMap);
    }

    @ApiOperation("增加系统用户")
    @PostMapping("saveUser")
    public R saveUser(@RequestBody JssXtUserlist jssXtUserlist) {
        QueryWrapper<JssXtUserlist> isExit = new QueryWrapper<>();
        isExit.eq("UserId", jssXtUserlist.getUserid());

        List<JssXtUserlist> list = jssXtUserlistService.list(isExit);
        if (list.size() > 0) {
            return R.ok().data("data", "用户已存在，");
        }
        QueryWrapper<JssXtUserlist> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("MAX(id) as id");
        JssXtUserlist serviceOne = jssXtUserlistService.getOne(queryWrapper);
        jssXtUserlist.setId((serviceOne.getId() + 1));
        jssXtUserlist.setDqzt("01");
        if (jssXtUserlistService.isRoleXiao()) {
            jssXtUserlist.setJb("校级");
            jssXtUserlist.setRole("普通");
        }
        boolean save = jssXtUserlistService.save(jssXtUserlist);
        return R.ok().data("data", "操作成功");
    }


    @ApiOperation("删除系统用户")
    @PostMapping("deleteUser/{id}")
    public R deleteUser(@PathVariable("id") Integer id) {
        if (id != null) {
            QueryWrapper<JssXtUserlist> userlistQueryWrapper = new QueryWrapper<>();
            userlistQueryWrapper.eq("id", id);
            jssXtUserlistService.remove(userlistQueryWrapper);
        }

        return R.ok().data("data", "操作成功");
    }
}